package com.bestcem.xm.user.service.impl.third;

import com.alibaba.fastjson.JSON;
import com.bestcem.xm.user.service.third.PhoneService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 外部手机号归属地查询服务
 *
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/2/23 17:26
 */
@Slf4j
@Service
public class PhoneServiceImpl implements PhoneService {
    @Value("${app.common.url360:http://cx.shouji.360.cn/phonearea.php?number=%s}")
    private String url360;

    @Value("${app.common.taobaourl:https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=%s}")
    private String taobaoUrl;

    @Resource
    private RestTemplate restTemplate;

    @Override
    public String getPhoneLocation(String phone) {
        //这里用CompletableFuture.anyOf 多优雅
        String url = String.format(url360, phone);
        String body = getRequest(url);

        String location = "";
        try {
            if (StringUtils.isNotEmpty(body)) {
                QueryData data = JSON.parseObject(body, QueryData.class);
                location = data.getData().getProvince() + data.getData().getCity();
            } else {
                url = String.format(taobaoUrl, phone);
                body = getRequest(url);
                if (StringUtils.isNotEmpty(body)) {
                    int start = body.indexOf("carrier:'");
                    int end = body.indexOf("'", start);
                    location = body.substring(start, end);
                }
            }
        } catch (Exception e) {
            log.error("[OM] 查询手机归属地失败,phone:{},e:{}", phone, e);
        }
        return StringUtils.isEmpty(location) ? "未知" : location;
    }

    private String getRequest(String url) {
        try {
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                return responseEntity.getBody();
            }
        } catch (Exception e) {
            log.error("[OM] 查询手机归属地失败,url:{},e:{}", url, e);
        }
        return "";
    }

    @Data
    private static class QueryData {
        private Location data;

        @Data
        private static class Location {
            private String province;
            private String city;
        }
    }
}
